package net.xo68.coordinator.core.gid;

import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;
import net.xo68.coordinator.core.rpc.ObjectSerialize;
import net.xo68.coordinator.core.rpc.ObjectSerializeFactory;
import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * 全局编号快照存储
 * @author wuxie
 * @version 2020-9-29
 */
@Slf4j
public class GidSnapshotStore {

    private final String path;

    public GidSnapshotStore(String path) {
        this.path = path;
    }

    public String getPath() {
        return path;
    }

    /**
     * Save value to snapshot file.
     * @param value
     * @return
     */
    public boolean save(GidData value) {
        try {
            log.info("\n save GidData:{}",value);
            ObjectSerialize objectSerialize= ObjectSerializeFactory.get();
            byte[] bytes=objectSerialize.serialize(value);
            FileUtils.writeByteArrayToFile(new File(path),bytes);
            return true;
        } catch (IOException e) {
            log.error("Fail to save snapshot", e);
            return false;
        }
    }

    public GidData load() throws IOException {
        byte[] bytes = FileUtils.readFileToByteArray(new File(path));
        ObjectSerialize objectSerialize= ObjectSerializeFactory.get();
        GidData gidData= objectSerialize.deserialize(bytes,GidData.class);
        log.info("\n load GidData:{}",gidData);
        return gidData;
    }

    @ToString
    @Data
    public static class GidData{
        private Map<Long,Long> data;

        public GidData() {
            this.data = new HashMap<>();
        }
    }
}
